package com.blitscreen.render 
{
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.utils.getTimer;
	
	import com.blitscreen.render.DrawPass;
	import com.bourre.collection.ArrayIterator;
	import com.bourre.collection.Iterable;
	import com.bourre.collection.Iterator;		

	/**
	 * @author Cedric Nehemie
	 */
	public class BasicDrawPass implements DrawPass, Iterable
	{
		protected var _nLastDrawTime : Number;		protected var _nLastDrawSpritesCount : Number;
		
		public var mergeAlpha : Boolean;
		
		protected var _aSprites : Array;

		public function BasicDrawPass ( mergeAlpha : Boolean = false )
		{
			this.mergeAlpha = mergeAlpha;
			_aSprites = new Array ();			
		}

		public function render ( screen : BitmapData ) : void
		{
			var ms : Number = getTimer();
			var n : Number = 0;
			var i : Iterator = iterator();
			var s : BlitSprite;
			var p : Point = new Point();
			
			while( i.hasNext() )
			{
				s = i.next() as BlitSprite;
				if( s.visible )
				{
					p.x = s.position.x - s.center.x;
					p.y = s.position.y - s.center.y;
					screen.copyPixels( s.bitmap, s.area, p, null, null, this.mergeAlpha );
				}
				n++;
			}
			
			_nLastDrawTime = getTimer() - ms;
			_nLastDrawSpritesCount = n;
		}

		public function add ( sprite : BlitSprite ) : void
		{
			if( !contains( sprite ) )
			{
				_aSprites.push( sprite );
			}
		}	
		public function addAt ( index : uint, sprite : BlitSprite ) : void
		{
			if( index < size() )
			{
				_aSprites.splice( index, 0, sprite );
			}
		}	
		public function remove ( sprite : BlitSprite ) : void
		{
			if( contains( sprite ) )
			{
				_aSprites.splice( _aSprites.indexOf( sprite ), 1 );
			}
		}
		public function removeAt ( index : uint ) : void
		{
			if( index < size() )
			{
				_aSprites.splice( index, 1 );
			}
		}
		public function removeAll () : void
		{
			_aSprites = new Array();
		}		
		public function hasSprites () : Boolean
		{
			return _aSprites.length != 0;
		}		

		public function getSprites () : Array
		{
			return _aSprites;
		}
		public function contains (sprite : BlitSprite) : Boolean
		{
			return _aSprites.indexOf( sprite ) != -1;
		}		
		public function size () : Number
		{
			return _aSprites.length;
		}
		public function iterator () : Iterator
		{
			return new ArrayIterator ( _aSprites );
		}

		public function getLastDrawTime () : Number
		{
			return _nLastDrawTime;
		}				
		public function getLastDrawSpritesCount () : Number
		{
			return _nLastDrawSpritesCount;
		}
	
	}
}
